import sqlite3
import db_config as config
from main_interface import log_init

service = sqlite3
global_con = None
global_cur = None


def create_connection():
    try:
        global global_con
        global global_cur
        conn = service.connect(config.DB_NAME)
        global_con = conn
        global_cur = global_con.cursor()
        return True
    except Exception, ex:
        log_init.show_log(ex)
        return False


def drop_all():
    try:
        if create_connection() == True:
            global_cur.execute("drop table " + config.QUEUE_TABLE)
            global_cur.execute("drop table " + config.VISITED_TABLE)
    except Exception, ex:
        log_init.show_log(ex)


def initialize():
    try:
        if create_connection() == True:
            global_cur.execute(config.QUEUE_CREATE_STMT)
            global_cur.execute(config.VISITED_CREATE_STMT)
            return True
        else:
            return False
    except Exception, ex:
        log_init.show_log(ex)
        log_init.show_log(config.VISITED_CREATE_STMT)
        return False


def insert_into_queue_tab(data):
    '''assumes the connection is already established'''
    try:
        global_con.executemany(config.QUEUE_INSERT_TEMPLATE, data)
        return True
    except Exception, ex:
        log_init.show_log(ex)


def exec_stmt(stmt):
    '''assumes the connection is already established'''
    try:
        ret = global_cur.execute(stmt)
        return (True, ret)
    except Exception, ex:
        return (False, None)


def get_rows(cur, batch=100):
    ret = []
    cnt = 0
    for row in cur:
        if cnt >= batch:
            break
        ret.append(row)
        cnt = cnt + 1
    if len(ret) > 0:
        return ret
    else:
        return None


if __name__ == "__main__":
    drop_all()
    ret = initialize()
    log_init.show_log(ret)
    data = [
            ('aaaa', 'bbbb'),
            ('kkk','mmm')
            ]
    for i in range(0,200):
        ret = insert_into_queue_tab(data)
    log_init.show_log(ret)
    stmt = "SELECT * FROM `" + config.QUEUE_TABLE + "`"
    ret = exec_stmt(stmt)
    if ret[0] == True:
        x = None
        while True:
            x = get_rows(ret[1])
            if x == None:
                break
            log_init.show_log(x)
            log_init.show_log(len(x))
